<script setup>
import { Editor } from '@wangeditor/editor-for-vue'
import { nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch } from 'vue'
import { useRoute } from 'vue-router'
import useArticleStore from '@/store/article/index.js'

const route = useRoute()
const id = route.query.id
console.log('id', id)

const articleStore = useArticleStore()
articleStore.detailAction(id)

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const mode = ref('default')

// 内容 HTML
const valueHtml = ref('<p></p>')

//文章发布
const title = ref()
setInterval(() => {
  valueHtml.value = articleStore.detail.content
  title.value = articleStore.detail.title
}, 100)

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...'
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

//自动聚焦文章标题
const inputRef = ref()
const focusInput = () => {
  nextTick(() => {
    inputRef.value.focus()
  })
}
onMounted(() => {
  focusInput()
})
</script>

<template>
  <div class="article">
    <div class="header"></div>
    <div class="edit">
      <el-input
        style="font-size: 22px; border-bottom: 1px solid #ccc; padding-bottom: 20px"
        ref="inputRef"
        size="large"
        v-model="title"
        placeholder="请输入文章标题"
      />
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
  </div>
</template>

<style scoped lang="less">
.article {
  padding-bottom: 50px;
  background-color: #f5f6f7;

  .header {
    display: flex;
    align-items: center;
    padding: 0 62px;
    height: 64px;

    .back-home {
      display: flex;
      align-items: center;
      margin-left: 200px;
      cursor: pointer;

      span {
        margin-left: 20px;
        font-weight: 700;
      }
    }

    .el-icon {
      background-color: rgb(245, 245, 245);
      border-radius: 50%;
      width: 24px;
      height: 24px;
      color: #222;
    }
  }

  .edit {
    background-color: white;
    margin: 0 auto;
    width: 800px;
    border: 1px solid #ccc;

    :deep(.el-input__wrapper) {
      box-shadow: none;
    }

    .el-input {
      margin-top: 20px;
    }
  }

  .edit-detail {
    margin: 0 auto;
    width: 800px;
  }

  .cover {
    width: 800px;
    display: flex;
    margin: 0 auto;
    margin-top: 20px;

    span {
      margin-right: 40px;
    }
  }

  .class-news {
    margin: 20px auto;
    width: 800px;

    span {
      margin-right: 40px;
    }
  }

  .btn {
    display: flex;
    margin: 20px auto;
    width: 800px;
    display: flex;
    justify-content: space-around;
  }
}
</style>
